import { Suspense, lazy } from 'react'
import { Routes, Route, Navigate } from 'react-router-dom'
import { Spin } from 'antd'
import { useAppStore } from '@/store/appStore'
import { autoRoutes } from './autoRoutes'

// 登录页面
const Login = lazy(() => import('@/pages/sys/login'))

// 错误页面
const NotFound = lazy(() => import('@/pages/error/404'))
const ServerError = lazy(() => import('@/pages/error/500'))
const ErrorPage = lazy(() => import('@/pages/error'))

// 布局组件
const Layout = lazy(() => import('@/components/Layout'))

// 加载组件
const Loading = () => (
  <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
    <Spin size="large" />
  </div>
)

export default function RouteView() {
  const isLogin = useAppStore((state) => state.isLogin())
  
  return (
    <Suspense fallback={<Loading />}>
      <Routes>
        <Route path="/login" element={<Login />} />
        
        <Route path="/" element={isLogin ? <Layout /> : <Navigate to="/login" />}>
          {autoRoutes.map((route) => (
            <Route
              key={route.path}
              path={route.path}
              element={<route.Component />}
            />
          ))}
          <Route index element={<Navigate to="/home" />} />
        </Route>
        
        <Route path="/404" element={<Suspense fallback={<Loading />}><NotFound /></Suspense>} />
        <Route path="/500" element={<Suspense fallback={<Loading />}><ServerError /></Suspense>} />
        <Route path="/error" element={<Suspense fallback={<Loading />}><ErrorPage /></Suspense>} />
        <Route path="*" element={<Navigate to="/404" />} />
      </Routes>
    </Suspense>
  )
}